-- UISkillUpgrade2
-- Created by chengb Mar/31/2015
-- 技能升级界面2（终极职业升级）

require "game/ui/form/hero/UISkillUpgradeSub"

UISkillUpgrade2 = class("UISkillUpgrade2", function()
    return cc.Layer:create();
end);

function UISkillUpgrade2.create(careerId)
    return UISkillUpgrade2.new(careerId);
end

-- 特性图标数量
local FEATURE_NUM = 3;

-- 内部函数声明
local resize;

function UISkillUpgrade2:ctor(careerId)
    -- 初始化
    self:setName("UISkillUpgrade2");
    local node = cc.CSLoader:createNode("layout/hero/SkillUpgrade2.csb");
    self:addChild(node);
    self.node = node;

    self.careerId = careerId;

    local pet = ME.user:getActivePet();
    self.pet = pet;

    -- 记录可选的特性列表
    local featureIds = CareerM.getFeatures(careerId);
    self.featureIds = featureIds;

    -- 检查当前携带的神器
    local curArtifact = ArtifactM.getCarryArtifact();
    local child = findChildByName(featureNode, "feature" .. 4);
    local cId = ArtifactM.query(curArtifact, "career_id");
    self.maxLevel = FormulaM.invoke("CALC_CAREER_STRENGTHEN_LEVEL", curArtifact);

    if self.careerId == cId and self.maxLevel > 0 then
        self.openFeature4 = true;
    else
        self.openFeature4 = false;
    end

    -- 需要显示在头部菜单上面
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
   -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UISkillUpgrade2:redraw()
    -- 重绘技能框
    self:redrawSkillInfo();

    -- 重绘按钮
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 获取基础属性值
function UISkillUpgrade2:getBasePropValue(baseProps, field)
    -- 需要先合并属性
    local value = 0;
    for _, arr in pairs(baseProps) do
        if arr[2] == field then
            value = value + arr[3];
        end
    end
    return value;
end

-- 重绘技能详细信息
function UISkillUpgrade2:redrawSkillInfo()

    local careerId = self.careerId;
    local careerInfo = CareerM.getCareerInfo(careerId);

    -- 显示职业名称
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    titleLabel:setString(careerInfo["name"]);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示标题栏中的星级图标
    local upperFeatureNum = self:getLevelUpperFeatureNum();
    local starNode = findChildByName(self.node, "CT/title_node/star_node");
    starNode:setScale(0.7);
    local curStar  = upperFeatureNum;
    local maxStar  = FEATURE_NUM;
    if self.maxLevel == 3 and self.openFeature4 then
        maxStar = maxStar + 1;
    end

    local lightStarPath = "images/ui/symbol/moon_01.png";
    local darkStarPath  = "images/ui/symbol/moon_02.png";
    local layer = createStarLayerEx(curStar, maxStar, lightStarPath, darkStarPath);
    if layer then
        starNode:removeAllChildren();
        starNode:addChild(layer);
    end

    -- 获取基础属性值
    local baseProps = CareerM.getFeatureBaseProps(self.pet.classId, self.careerId, true, true);

    -- 显示基础属性
    local basePropNode = findChildByName(self.node, "CT/base_prop_node");

    -- 攻击
    local nameLabel  = findChildByName(basePropNode, "attack_node/name");
    local valueLabel = findChildByName(basePropNode, "attack_node/value");
    nameLabel:setString(getLocStr("attack"));
    local value = self:getBasePropValue(baseProps, "attack");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    if value <= 0 then
        valueLabel:setString(getLocStr("default_value_text"));
    else
        valueLabel:setString("+" .. value);
    end

    -- 生命
    nameLabel  = findChildByName(basePropNode, "hp_node/name");
    valueLabel = findChildByName(basePropNode, "hp_node/value");
    nameLabel:setString(getLocStr("hp"));
    local value = self:getBasePropValue(baseProps, "max_hp");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    if value <= 0 then
        valueLabel:setString(getLocStr("default_value_text"));
    else
        valueLabel:setString("+" .. value);
    end

    -- 魔力
    nameLabel  = findChildByName(basePropNode, "magic_node/name");
    valueLabel = findChildByName(basePropNode, "magic_node/value");
    nameLabel:setString(getLocStr("magic"));
    local value = self:getBasePropValue(baseProps, "magic");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    if value <= 0 then
        valueLabel:setString(getLocStr("default_value_text"));
    else
        valueLabel:setString("+" .. value);
    end

    -- 魔法
    nameLabel  = findChildByName(basePropNode, "mp_node/name");
    valueLabel = findChildByName(basePropNode, "mp_node/value");
    nameLabel:setString(getLocStr("mp"));
    local value = self:getBasePropValue(baseProps, "max_mp");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    if value <= 0 then
        valueLabel:setString(getLocStr("default_value_text"));
    else
        valueLabel:setString("+" .. value);
    end

    -- 显示职业特性描述
    local propLabel = findChildByName(self.node, "CT/prop_desc");
    local propStr = CareerM.getFeatureDesc(self.pet.classId, self.careerId, true);

    TextStyleM.setTextStyle(propLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(propLabel, propStr);

    -- 显示特性信息特性信息
    self:redrawFeatures();

    -- 显示背景称号图标
    -- 放放、半透明显示
    local bgIconImg = findChildByName(self.node, "CT/bg_icon");
    bgIconImg:loadTexture(getCareerIconPath(careerInfo["icon"]));
    bgIconImg:setScale(1.8);
    bgIconImg:setOpacity(50);
end

-- 获取已满级的特性数量
function UISkillUpgrade2:getLevelUpperFeatureNum()
    local total = 0;
    for i = 1, #self.featureIds do
        local id = self.featureIds[i];
        local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, id, true);

        local skillId = featureInfo["skill_id"];
        local skillInfo = SkillM.query(skillId);

        if featureInfo["top_level"] == 1 then
            total = total + 1;
        end
    end

    return total;
end

-- 显示特性信息
function UISkillUpgrade2:redrawFeatures()
    local featureNode = findChildByName(self.node, "CT/feature_node");
    local totalNum = #self.featureIds;

    local kerning = 0;
    if getLang() == "fr" then
        kerning = -2;
    end

    for i = 1, FEATURE_NUM do
        local child = findChildByName(featureNode, "feature" .. i);

        if i > totalNum then
            child:setVisible(false);
        else
            child:setVisible(true);
            local nameLabel = findChildByName(child, "name");
            local starNode = findChildByName(child, "star_node");

            local id = self.featureIds[i];
            local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, id, true);

            local skillId = featureInfo["skill_id"];
            local skillInfo = SkillM.query(skillId);
            local isNewSkill = iif(featureInfo["is_new_skill"] == 1, true, false);

            -- 显示技能名称
            local skillName = skillInfo["name"];
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning, nil, nil, nil, nil, true, TextStyleM.getTextScale(skillName, 6 * 2));
            TextStyleM.setShadowStyle(nameLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_OUTLINE_COLOR);
            TextStyleM.setOutlineStyle(nameLabel, 1, TextStyleM.TEXT_OUTLINE_COLOR, true);
            nameLabel:setString(skillName);

            local curStar = iif(isNewSkill, 0, skillInfo["level"]);
            local maxStar = featureInfo["max_level"];
            local lightStarPath = "images/ui/symbol/star_large.png";
            local darkStarPath  = "images/ui/symbol/star_large2.png";
            local layer = createStarLayerEx(curStar, maxStar, lightStarPath, darkStarPath);
            if layer then
                starNode:removeAllChildren();
                starNode:addChild(layer);
            end
        end
    end

    -- 检查当前携带的神器
    local child = findChildByName(featureNode, "feature4");
    if self.openFeature4  then
        child:setVisible(true);

        local nameLabel = findChildByName(child, "name");
        local starNode = findChildByName(child, "star_node")

        local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, 4, true);

        local skillId = featureInfo["skill_id"];
        local skillInfo = SkillM.query(skillId);
        local isNewSkill = iif(featureInfo["is_new_skill"] == 1, true, false);

        -- 显示技能名称
        local skillName = skillInfo["name"];
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning, nil, nil, nil, nil, true, TextStyleM.getTextScale(skillName, 6 * 2));
        TextStyleM.setShadowStyle(nameLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_OUTLINE_COLOR);
        TextStyleM.setOutlineStyle(nameLabel, 1, TextStyleM.TEXT_OUTLINE_COLOR, true);
        nameLabel:setString(skillName);

        local curStar = iif(isNewSkill, 0, skillInfo["level"]);
        local maxStar = featureInfo["max_level"];

        local lightStarPath = "images/ui/symbol/star_large.png";
        local darkStarPath  = "images/ui/symbol/star_large2.png";
        local layer = createStarLayerEx(curStar, self.maxLevel, lightStarPath, darkStarPath);
        if layer then
            starNode:removeAllChildren();
            starNode:addChild(layer);
        end

        -- 按钮节点整体向上挪一点

        if not featureNode.initY then
            featureNode.initY = featureNode:getPositionY();
        end

        featureNode:setPositionY(featureNode.initY + 30);
    else
        child:setVisible(false);
    end
end

-- 注册点击事件
function UISkillUpgrade2:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkillUpgrade2");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册特性图标点击事件
    local featureNode = findChildByName(self.node, "CT/feature_node");
    for i = 1, FEATURE_NUM do
        local child = findChildByName(featureNode, "feature" .. i);
        local btn = findChildByName(child, "btn");
        local function onClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                local featureId = self.featureIds[i];
                if CareerM.isFeatureMaxLevel(self.pet, self.careerId, featureId) then
                    -- 该特性已满级
                    local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, featureId, true);
                    local skillId = featureInfo["skill_id"];
                    local skillInfo = SkillM.query(skillId);
                    local skillName = skillInfo["name"];
                    local msg = string.format(getLocStr("feature_lever_upper"), skillName);

                    alert(msg);
                    return;
                end

                -- 打开升级子界面
                UIMgr.getCurrentScene():removeFormByName("UISkillUpgradeSub");
                local uiSkillUpgradeSub = UISkillUpgradeSub.create(self.careerId, featureId);
                UIMgr.getCurrentScene():addForm(uiSkillUpgradeSub);
            end
        end
        btn:addTouchEventListener(onClick);
    end

    if self.openFeature4 then
        local child = findChildByName(featureNode, "feature4");
        local btn = findChildByName(child, "btn");
        local function onClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, 4, true);

                local skillId = featureInfo["skill_id"];
                local skillInfo = SkillM.query(skillId);
                local isNewSkill = iif(featureInfo["is_new_skill"] == 1, true, false);

                local curLevel = iif(isNewSkill, 0, skillInfo["level"]);

                if CareerM.isFeatureMaxLevel(self.pet, self.careerId, 4) or  curLevel >= self.maxLevel then
                    -- 该特性已满级
                    local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, 4, true);
                    local skillId = featureInfo["skill_id"];
                    local skillInfo = SkillM.query(skillId);
                    local skillName = skillInfo["name"];
                    local msg = string.format(getLocStr("feature_lever_upper"), skillName);

                    alert(msg);
                    return;
                end

                -- 打开升级子界面
                UIMgr.getCurrentScene():removeFormByName("UISkillUpgradeSub");
                local uiSkillUpgradeSub = UISkillUpgradeSub.create(self.careerId, 4);
                UIMgr.getCurrentScene():addForm(uiSkillUpgradeSub);
            end
        end
        btn:addTouchEventListener(onClick);
    end
end

-- 注册事件处理回调函数
function UISkillUpgrade2:registerEventCallback()
    EventMgr.register("UISkillUpgrade2", event.UPGRADE_CAREER, function(args)
        local careerId  = args.careerId;
        local level     = args.level;
        local featureId = args.feature;

        if table.indexOf(self.featureIds, featureId) == -1 and featureId ~= 4 then
            -- 不是特性升级，不处理
            return;
        end

        -- 提示特性等级提升
        local careerName  = CareerM.getCareerInfo(careerId, "name");
        local featureInfo = CareerM.getFeatureInfo(self.pet, self.careerId, featureId, true);
        local skillId   = featureInfo["skill_id"];
        local skillInfo = SkillM.query(skillId);
        local skillName = skillInfo["name"];
        local level     = skillInfo["level"];
        local msg = string.format(getLocStr("feature_upgrade_succ"), careerName, skillName, level);

        alert(msg);

        -- 刷新界面
        self:redraw();

        -- 重绘界面
        EventMgr.fire(event.JOIN_CAREER_ANIM_DONE);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UISkillUpgrade2");
        end
    end);
end